package com.sgb.kjwl.view.widget;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;

import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.view.TimePickerView;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ItemSelfTeamWorkerProjectBinding;
import com.sgb.kjwl.model.entity.self.SelfTeamWorkerAddEntity;
import com.sgb.kjwl.model.entity.user.AddressEntity;
import com.swgk.core.customview.ItemInputTextView;
import com.swgk.core.util.DateUtils;
import com.swgk.core.util.MToast;
import com.swgk.core.view.CityPickBuilder;
import com.swgk.core.view.CityPickView;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

public class SelfTeamWorkerProjectView extends LinearLayout implements ItemInputTextView.OnWholeItemClickListener {

    private ItemSelfTeamWorkerProjectBinding mBind;

    private SelfTeamWorkerAddEntity.WorkExpListBean mListBean;

    private Context context;

    private long startTime = 0;

    // 一级联动数据
    private List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> addressEntityList;
    // 二级联动数据
    private List<List<AddressEntity<List<AddressEntity>>>> opt2 = new ArrayList<>();
    // 三级联动数据
    private List<List<List<AddressEntity>>> opt3 = new ArrayList<>();

    private Thread thread;
    private static final int MSG_LOAD_DATA = 0x0001;
    private static final int MSG_LOAD_SUCCESS = 0x0002;
    private boolean isLoaded = false;

    private int cityPosition1;
    private int cityPosition2;
    private int cityPosition3;

    public SelfTeamWorkerProjectView(Context context) {
        this(context, null);
    }

    public SelfTeamWorkerProjectView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public SelfTeamWorkerProjectView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.context = context;
        init(context);
    }

    private void init(Context context) {
        mBind = DataBindingUtil.inflate(LayoutInflater.from(context), R.layout.item_self_team_worker_project, this, true);
        mBind.etStartTime.setOnWholeItemClickListener(this);
        mBind.etOverTime.setOnWholeItemClickListener(this);
        mBind.etAddress.setOnWholeItemClickListener(this);
    }

    public void setBean(SelfTeamWorkerAddEntity.WorkExpListBean listBean, int size, List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> data) {
        if (listBean == null) {
            mListBean = new SelfTeamWorkerAddEntity.WorkExpListBean();
        } else {
            mListBean = listBean;
            mBind.etStartTime.setContent(DateUtils.timestampToDate(listBean.getStartTime()));
            mBind.etOverTime.setContent(DateUtils.timestampToDate(listBean.getEndTime()));
            mBind.etAddress.setContent(listBean.getProvinceName() + listBean.getCityName() + listBean.getAreaName());
        }
        this.addressEntityList = data;
        mBind.setViewModel(listBean);
        mBind.etPro.setLabelName("工作经验" + size);
    }

    public SelfTeamWorkerAddEntity.WorkExpListBean getListBean() {
        String name = mBind.etProName.getContent();
        if (!TextUtils.isEmpty(name)) {
            mListBean.setProjectName(name);
        }
        String proDes = mBind.etProDes.getEditContent();
        if (!TextUtils.isEmpty(proDes)) {
            mListBean.setContent(proDes);
        }
        return mListBean;
    }

    @Override
    public void OnWholeItemClick(View view) {
        switch (view.getId()) {
            case R.id.et_start_time:
                showTimePop(1);
                break;
            case R.id.et_over_time:
                showTimePop(2);
                break;
            case R.id.et_address:
                showAddressPop();
                break;
        }
    }

    //时间选择器
    public void showTimePop(int flag) {
        TimePickerBuilder timePickerBuilder = new TimePickerBuilder(context, (date, v) -> {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String format = sdf.format(date);

            try {
                if (flag == 1) {
                    long times = DateUtils.dateTo13Timestamp(format);
                    startTime = times;
                    mBind.etStartTime.setContent(format);
                    mListBean.setStartTime(times);
                }
                if (flag == 2) {
                    long times = DateUtils.dateTo13Timestamp(format);
                    long ls = DateUtils.dateTo10Timestamp(DateUtils.timestampToDate(times));
                    long le = DateUtils.dateTo10Timestamp(DateUtils.timestampToDate(startTime));
                    if (ls <= le) {
                        MToast.showToast(context, "请选择大于开工时间的日期");
                    } else {
                        mBind.etOverTime.setContent(format);
                        mListBean.setEndTime(times);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).setType(new boolean[]{true, true, true, false, false, false});

        Calendar selectedDate = Calendar.getInstance();
        Calendar startDate = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String format = sdf.format(new Date());
        String[] split = format.split("-");
        startDate.set(Integer.parseInt(split[0]), Integer.parseInt(split[1]) - 1, Integer.parseInt(split[2]));//设置起始年份
        Calendar endDate = Calendar.getInstance();
        endDate.set(2099, 11, 31);//设置结束年份

        timePickerBuilder.setRangDate(startDate, endDate);
        TimePickerView timePicker = timePickerBuilder.build();
        timePicker.show();
        timePicker.setDate(selectedDate);
    }

    @SuppressWarnings("unchecked")
    public void showCityPop() {
        //条件选择器
        CityPickView cityOption = new CityPickBuilder(context, (options1, options2, options3, v) -> {
            String areaName;
            if (opt3.get(options1).get(options2).get(options3) == null) {
                areaName = "";
            } else {
                areaName = opt3.get(options1).get(options2).get(options3).getName();
                cityPosition3 = options3;
                mListBean.setAreaNo(opt3.get(options1).get(options2).get(options3).getNo());
                mListBean.setAreaName(areaName);
            }
            String content = addressEntityList.get(options1).getName()
                    + opt2.get(options1).get(options2).getName()
                    + areaName;
            mBind.etAddress.setContent(content);
            cityPosition1 = options1;
            cityPosition2 = options2;
            mListBean.setProvinceName(addressEntityList.get(options1).getName());
            mListBean.setProvinceNo(addressEntityList.get(options1).getId());
            mListBean.setCityName(opt2.get(options1).get(options2).getName());
            mListBean.setCityNo(opt2.get(options1).get(options2).getNo());
        }).build();
        cityOption.setPicker(addressEntityList, opt2, opt3);
        cityOption.setSelectOptions(cityPosition1, cityPosition2, cityPosition3);
        cityOption.show();
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_LOAD_DATA:
                    if (thread == null) {//如果已创建就不再重新创建子线程了
                        thread = new Thread(() -> {
                            // 子线程中解析省市区数据
                            initJsonData();
                        });
                        thread.start();
                    }
                    break;
                case MSG_LOAD_SUCCESS:
                    showCityPop();
                    isLoaded = true;
                    thread = null;
                    break;
            }
        }
    };

    private void initJsonData() {
        //城市列表
        @SuppressWarnings("MismatchedQueryAndUpdateOfCollection") List<AddressEntity<List<AddressEntity>>> cityList;
        //区域列表
        List<List<AddressEntity>> areaList;
        for (int x = 0; x < addressEntityList.size(); x++) {
            cityList = new ArrayList<>();
            areaList = new ArrayList<>();
            if (mListBean != null && mListBean.getProvinceName() != null && mListBean.getProvinceName().equals(addressEntityList.get(x).getName())) {
                cityPosition1 = x;
            }
            opt2.add(addressEntityList.get(x).getChildren());
            for (int i = 0; i < addressEntityList.get(x).getChildren().size(); i++) {
                cityList.add(addressEntityList.get(x).getChildren().get(i));
                List<AddressEntity> cityAreaList = new ArrayList<>();
                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (addressEntityList.get(x).getChildren().get(i).getChildren() == null
                        || addressEntityList.get(x).getChildren().get(i).getChildren().size() == 0) {
                    cityAreaList.add(null);
                } else {
                    cityAreaList.addAll(addressEntityList.get(x).getChildren().get(i).getChildren());
                }
                areaList.add(cityAreaList);
            }
            opt3.add(areaList);
        }
        if (mListBean != null) {
            if (mListBean.getCityName() != null)
                for (int x2 = 0; x2 < opt2.size(); x2++) {
                    if (mListBean.getCityName().equals(addressEntityList.get(cityPosition1).getChildren().get(x2).getName())) {
                        cityPosition2 = x2;
                        break;
                    }
                }
            if (mListBean.getAreaName() != null)
                for (int x3 = 0; x3 < opt3.size(); x3++) {
                    if (mListBean.getAreaName().equals(addressEntityList.get(cityPosition1).getChildren().get(cityPosition2).getChildren().get(x3).getName())) {
                        cityPosition3 = x3;
                        break;
                    }
                }
        }
        mHandler.sendEmptyMessage(MSG_LOAD_SUCCESS);
    }

    //所在地区选择
    public void showAddressPop() {
        if (isLoaded) {
            showCityPop();
        } else {
            mHandler.sendEmptyMessage(MSG_LOAD_DATA);
        }
    }
}
